package com.agentai.framework.mybatis.handler;

import com.agentai.framework.satoken.helper.MpLoginHelper;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.agentai.framework.security.user.UserDetail;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * mybatis-plus 自动填充字段
 */
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_TIME = "createTime";
    private final static String CREATOR = "creator";
    private final static String CREATEBY = "createBy";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATER = "updater";
    private final static String UPDATEBY = "updateBy";
    private final static String ORG_ID = "orgId";
    private final static String VERSION = "version";
    private final static String DELETED = "deleted";

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = MpLoginHelper.getLoginUser();
        LocalDateTime now = LocalDateTime.now();

        // 用户字段填充
        if (user != null) {
            // 创建者ID
            setFieldValByName(CREATOR, user.getId(), metaObject);
            // 创建者用户名
            setFieldValByName(CREATEBY, user.getRealName(), metaObject);
            // 更新者ID
            setFieldValByName(UPDATER, user.getId(), metaObject);
            // 更新者用户名
            setFieldValByName(UPDATEBY, user.getRealName(), metaObject);
            // 创建者所属机构
            setFieldValByName(ORG_ID, user.getOrgId(), metaObject);
        }

        // 创建时间
        setFieldValByName(CREATE_TIME, now, metaObject);
        // 更新时间
        setFieldValByName(UPDATE_TIME, now, metaObject);
        // 版本号
        setFieldValByName(VERSION, 0, metaObject);
        // 删除标识
        setFieldValByName(DELETED, 0, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新者ID
         Long userId =0L;
        try {
             userId = MpLoginHelper.getUserId();
        }catch (Exception e){
        }
        setFieldValByName(UPDATER, userId, metaObject);
        // 更新者用户名
        String realName = "";
        try {
             realName = MpLoginHelper.getRealName();
        }catch (Exception e){

        }
        setFieldValByName(UPDATEBY, realName, metaObject);
        // 更新时间
        setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
    }
}
